# -*- encoding: utf-8 -*-
import re
import json
import requests
from bs4 import BeautifulSoup
from .result import result

CHECK_SSFW_URL = 'http://ssfw.hlju.edu.cn/ssfw/j_spring_ids_security_check'
SCORE_URL = 'http://ssfw.hlju.edu.cn/ssfw/zhcx/cjxx.do'


def request_scores(uid,token):
    cookie = {'iPlanetDirectoryPro':token}

    data = None
    for i in range(10):
        print('request scores: ',i)
        if data != None:
            break
        try:
            session = requests.session()
            session.get(CHECK_SSFW_URL,cookies = cookie,timeout=2)
            req = session.get(SCORE_URL,cookies = cookie,timeout=2)

            # if has Content-Length attribute,means didnt get real data
            if req.headers.get('Content-Length') != None:
                continue

            html = req.content
        except requests.Timeout as e:
            print('timeout')
            continue

        except requests.ConnectionError as e:
            return result(107)

        except Exception as e:
            print(e)
            return result(105)

        data = parse_score(uid,html)

    # if there still have no data after 10 times tried, it means verify expired
    if data == None:
        return result(108)

    return result(100,data)



#解析成绩表
def parse_score(uid,html):

	table = BeautifulSoup(html,'html.parser').find('table',{'class':'ui_table ui_table_hover ui_table_striped ui_table_style02'})
	if table == None:
		return None

	trs = table.find_all('tr')

	json_list = []
	for tr in trs:
		item_list = tr.find_all('td')
		if len(item_list) < 8:
			continue

		terms = item_list[1].get_text(strip = True).split(' ')

		schoolYear = '--' if len(terms) < 2 else terms[0]
		term = '--' if len(terms) < 2 else terms[1]

		# term = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
		cid = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
		cn = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)

		cty = '--' if len(item_list[4].get_text(strip = True)) == 0 else item_list[4].get_text(strip = True)
		cp = '--' if len(item_list[5].get_text(strip = True)) == 0 else item_list[5].get_text(strip = True)

		credit = 0.0 if len(item_list[6].get_text('|',strip = True).split('|')[0]) == 0 else float(item_list[6].get_text('|',strip = True).split('|')[0])
		score = float(re.compile(r'\d{1,3}').findall(item_list[7].text)[0])
		sm = '初修' if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)

		json_list.append({'uid':uid,'schoolYear':schoolYear,'term':term,'cid':cid,'cname':cn,'type':cty,
		'property':cp,'credit':credit,'score':score,'studyMethod':sm})

	return json_list

if __name__ =='__main__':
    data=request_scores('20135081','AQIC5wM2LY4Sfcw1LQpOUCsV8Zuz0KwAWjIwouJN7Hn1YSA%3D%40AAJTSQACMDI%3D%23').encode('utf-8')
    print(data)
